package com.itheima.reggie.filter;


import com.alibaba.fastjson2.JSON;
import com.itheima.reggie.utils.BaseContext;
import com.itheima.reggie.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证过滤器
 * 配置过滤器拦截的访问路径为/*
 */
@WebFilter("/*")
@Slf4j
public class LoginFilter implements Filter {

    // 定义路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 放行前逻辑,一般对request数据进行处理
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 定义与登录注册有关的uri(不需要登录)
        String[] requestURIs = new String[]{
                "/backend/**",
                "/employee/login",
                "/employee/logout",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}", requestURI);
        // 不需要登录的uri直接放行
        if (check(requestURI, requestURIs)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 需要登录的uri,并且已经登录
        if (request.getSession().getAttribute("employeeId") != null) {
            Long employeeId = (Long) request.getSession().getAttribute("employeeId");
            BaseContext.setCurrentId(employeeId);
            // 放行
            filterChain.doFilter(request, response);
            // 放行后逻辑,一般对response数据进行处理
            return;
        }
        if (request.getSession().getAttribute("userId") != null) {
            Long userId = (Long) request.getSession().getAttribute("userId");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        // 需要登录的uri,但是没有登录
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    public boolean check(String requestURI, String[] requestURIs) {
        for (String URI : requestURIs) {
            if (PATH_MATCHER.match(URI, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
